<?php

namespace WxWorkSDK\Department;

use WxWorkSDK\Error\Error;
use WxWorkSDK\Http\Http;
use WxWorkSDK\Result;

/**
 * Class GetDepartment
 * @package  WxWorkSDK\Department
 * @author   George
 * @datetime 2019/5/30 11:16
 * @annotation
 */
class GetDepartment
{
    const URI = "department/list";
    /**
     * @var string
     * @annotation
     */
    public $id = '';
    /**
     * @var string
     * @annotation
     */
    public $accessToken = "";

    /**
     * GetDepartment constructor.
     * @param string $id
     * @param string $accessToken
     */
    public function __construct(string $id, string $accessToken)
    {
        $this->id          = $id;
        $this->accessToken = $accessToken;
    }

    /**
     * @return Result
     * @annotation
     */
    public function getList(): Result
    {
        if (empty($this->id)) {
            return new Result(FALSE, Error::PARAM_MISTAKE, '无部门ID');
        }
        if (empty($this->accessToken)) {
            return new Result(FALSE, Error::PARAM_MISTAKE, '无TOKEN');
        }
        list($bool, $response) = Http::request('GET', self::URI, ["query" => [
            "access_token" => $this->accessToken, "id" => $this->id]]);
        if (!$bool) {
            return $response;
        } else {
            return $this->response($response);
        }
    }

    /**
     * @param $response
     * @return Result
     * @annotation
     */
    private function response($response): Result
    {
        $response = json_decode($response, TRUE);
        if ($response['errcode'] == 0) {
            return new Result(TRUE, 0, 'ok', $response['department']);
        } else {
            return new Result(FALSE, Error::WX_MISTAKE, $response['errcode'] . ':' . $response['errmsg']);
        }
    }
}